<template>
  <div class="crud-opts">
    <span class="crud-flex">
      <!--左侧插槽-->
      <slot name="left"/>
      <img class="img" src="@images/update.png" alt="" @click="doReply()">
      <img class="img" src="@images/beifen.png" alt=""
           v-permission="permission.backUp==undefined ? ['']:permission.backUp" @click="toBackUp()">
      <el-popover placement="bottom-end" width="150" style="height:30px" trigger="click">
        <img class="img" aria-hidden="true" slot="reference" src="@images/gezi.png" alt="">
        <el-checkbox v-model="allColumnsSelected" :indeterminate="allColumnsSelectedIndeterminate"
                     @change="handleCheckAllChange">
          全选
        </el-checkbox>
        <el-checkbox v-for="(item,i) in crud.props.tableColumns" :key="i" v-model="item.visible"
                     @change="handleCheckedTableColumnsChange(item)">
          {{ item.label }}
        </el-checkbox>
      </el-popover>

      <el-popover v-if="moreQueryList != null" placement="bottom-start" width="888" style="height:30px" trigger="click"
                  ref="popoverName">
        <img class="img" slot="reference" src="@images/shaixuan.png" alt="">
        <div>
          <el-form ref="form" :model="queryForm" label-position="right" label-width="100px"
                   style="max-height: 310px;overflow-y: auto;">
            <div v-for="(item, index) in moreQueryList" :key="index">
              <el-row v-if="item.type == 'textarea'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-input type="textarea" :rows="2" :placeholder="item.placeholder"
                              v-model.trim="queryForm[item.cloumLable]" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'input'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-input v-model.trim="queryForm[item.cloumLable]" :placeholder="item.placeholder"/>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'select'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-select v-model="queryForm[item.cloumLable]" :placeholder="item.placeholder">
                      <el-option v-for="(ob,i) in allApp" :key="i" :label="ob.appName" :value="ob.appCode">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'radio'">
                <el-col :span="20">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-radio-group v-model="queryForm[item.cloumLable]" size="medium">
                      <el-radio-button v-for="(ob,i) in item.radioList" :key="i"
                                       :label="ob.label">{{ ob.value }}</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'datePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateChange(item.cloumLable)"
                                    value-format="yyyyMMdd" type="date" placeholder="选择日期" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">今天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">昨天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]" @change="fastDate(item.cloumLable,index * 10 + 2)"
                            :label="index * 10 + 2">前天</el-radio>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'dateNoTimePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateChange(item.cloumLable)"
                                    value-format="yyyyMMdd" type="daterange" range-separator="至"
                                    start-placeholder="开始时间" end-placeholder="结束时间" style="width: 400px;"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectDateFramePicker(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">本周</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectDateFramePicker(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">本月</el-radio>
                </el-col>
              </el-row>
              <el-row v-if="item.type == 'timeFramePicker'">
                <el-col :span="14">
                  <el-form-item :label="item.name" :prop="item.cloumLable" class="item">
                    <el-date-picker v-model="queryForm[item.cloumLable]" @change="dateTimeRangeChange(item.cloumLable)"
                                    value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange" range-separator="至"
                                    start-placeholder="开始时间" end-placeholder="结束时间"/>
                  </el-form-item>
                </el-col>
                <el-col :span="10" style="padding-left: 20px;line-height: 33px;">
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 0)"
                            :label="index * 10 + 0">今天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 1)"
                            :label="index * 10 + 1">昨天</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 2)"
                            :label="index * 10 + 2">本周</el-radio>
                  <el-radio v-model="queryForm[item.cloumLableType]"
                            @change="selectTimeFramePicker(item.cloumLable,index * 10 + 3)"
                            :label="index * 10 + 3">本月</el-radio>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <el-row style="border-top: 1px solid #EBEEF5;padding-top: 10px;text-align: center;">
            <el-button @click="doReset" style="width: 80px;">重置</el-button>
            <el-button type="primary" @click="doMoreQuery" style="width: 80px;">查询</el-button>
          </el-row>
        </div>
      </el-popover>
      <el-button-group v-if="moreQueryList == null" style="height:30px">
        <img class="img" src="@images/search.png" @click="toggleSearch()" v-if="crud.props.searchToggle" alt="">
        <div style="display: inline-block;" class="el-button-group-search select">
          <img class="img" style="margin-right:0px !important" v-if="!crud.props.searchToggle" src="@images/hidden.png"
               alt="" @click="toggleSearch()">
          <el-input placeholder="请输入内容" v-model="qryParam" style="width: 300px;" class="input-with-select"
                    @change="paramChange" v-if="!crud.props.searchToggle" clearable>
            <el-select v-model="qryCloum" @change="cloumChange" slot="prepend" placeholder="请选择" style="width: 100px">
              <el-option v-for="(item, i) in crud.queryList" :label="item.cloumName" :key="i"
                         :value="item.cloumValue"></el-option>
            </el-select>
          </el-input>
          <img class="img" v-if="!crud.props.searchToggle" slot="append" src="@images/search.png" alt=""
               @click="doQuery">
        </div>
      </el-button-group>
      <!--右侧-->
      <slot name="right"/>
    </span>
    <el-button-group class="crud-opts-right">
      <el-pagination :page-size.sync="page.size" :total="page.total" :page-sizes="[10, 50, 100, 300, 500, 1000]"
                     :current-page.sync="page.page" style="margin-top: 8px;" layout="prev, pager, next,sizes,total"
                     @size-change="crud.sizeChangeHandler($event)" @current-change="crud.pageChangeHandler"
                     :pager-count="5" prev-text=" " next-text=" "/>
    </el-button-group>
  </div>
</template>

<script>
import CRUD, {crud, pagination} from "@crud/crud";
import config from '@/settings'

const dateOffset = config.dateOffset

export default {
  mixins: [crud(), pagination()],
  filters: {
    formatTime: function (value) {
      if (value != '') {
        return value.slice(0, 19).replace('T', ' ')
      }
    }
  },
  props: {
    permission: {
      type: Object,
      default: null
    },
    defaultQueryForm: {
      type: Object,
      default: null
    },
    moreQueryList: null,
    allApp: []
  },
  data() {
    return {
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      qryParam: "",
      qryCloum: "",
      queryForm: {},
    };
  },
  created() {
    this.crud.updateProp("searchToggle", true);
    if (this.crud.params.bizDate == '' || this.crud.params.bizDate) {
      this.queryForm = this.crud.params
    } else {
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
    }
  },
  methods: {
    init() {
      this.crud.query.bizDate = this.currentDate()
      this.crud.toQuery()
    },
    currentDate() {
      let timestamp = Date.now() + dateOffset * 1000 * 60 * 60 * 24
      let date = new Date(timestamp)
      let year = date.getFullYear()
      let month = ('0' + (date.getMonth() + 1)).slice(-2)
      let sdate = ('0' + date.getDate()).slice(-2)
      let result = year + month + sdate
      return result
    },
    toBackUp() {
      this.crud.backUp = true
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.$message({
          message: '请至少选择一列',
          type: 'warning'
        });
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val;
      }
      this.allColumnsSelected = val;
      this.allColumnsSelectedIndeterminate = false;
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0;
      let selectedCount = 0;
      for (const key in this.crud.props.tableColumns) {
        ++totalCount;
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0;
      }
      if (selectedCount === 0) {
        this.crud.notify("请至少选择一列", CRUD.NOTIFICATION_TYPE.WARNING);
        this.$nextTick(function () {
          item.visible = true;
        });
        return;
      }
      this.allColumnsSelected = selectedCount === totalCount;
      this.allColumnsSelectedIndeterminate =
        selectedCount !== totalCount && selectedCount !== 0;
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle;
    },
    paramChange(value) {
      this.qryParam = value;
    },
    cloumChange(value) {
      this.qryCloum = value;
      for (let key in this.crud.query) {
        if (key != this.qryCloum) {
          delete this.crud.query[key]
        }
      }
    },
    doReply() {
      this.crud.findVM('presenter').$refs['table'].clearFilter()
      this.crud.query = {}
      this.qryParam = ''
      this.qryCloum = ''
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
      this.crud.params = {}
      this.init()
    },
    doQuery() {
      var key = "";
      var value = "";
      if (this.qryCloum == null || this.qryCloum == '') {
        this.$message({
          message: '请先选择搜索项',
          type: 'warning'
        });
        return;
      }
      if (this.qryCloum != null && this.qryCloum != "") {
        key = this.qryCloum;
      }
      if (this.qryParam != "" && this.qryParam != null) {
        value = this.qryParam;
      }
      this.crud.query[key] = value;
      this.crud.toQuery();
    },
    fastDate(cloum, index) {
      index = index % 10;
      this.queryForm[cloum] = this.$moment().add(-index, 'days').format('YYYYMMDD');
    },
    selectTimeFramePicker(cloum, index) {
      index = index % 10;
      if (0 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (1 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().add(-1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().add(-1, 'days').endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (2 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('isoWeek').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
      if (3 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('month').format('YYYY-MM-DD HH:mm:ss'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYY-MM-DD HH:mm:ss'));
      }
    },
    selectDateFramePicker(cloum, index) {
      index = index % 10;
      if (0 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('isoWeek').format('YYYYMMDD'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYYMMDD'));
      }
      if (1 == index) {
        this.queryForm[cloum] = [];
        this.queryForm[cloum].push(this.$moment().startOf('month').format('YYYYMMDD'));
        this.queryForm[cloum].push(this.$moment().endOf('day').format('YYYYMMDD'));
      }
    },
    doReset() {
      this.queryForm = JSON.parse(JSON.stringify(this.defaultQueryForm));
      this.doMoreQuery();
    },
    doMoreQuery() {
      this.$refs['popoverName'].doClose()
      this.crud.page.page = 1;
      this.crud.params = JSON.parse(JSON.stringify(this.queryForm));
      this.crud.toQuery();
    },
    dateChange(cloumLable) {
      let cloum = cloumLable + "Type";
      this.queryForm[cloum] = null;
    },
    dateTimeRangeChange(cloumLable) {
      let cloum = cloumLable + "Type";
      this.queryForm[cloum] = null;
    },
  }
};
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}

.item .el-form-item__label {
  font-weight: 100;
}

.crud-opts-left {
  display: flex;
  align-items: center;
}
</style>
